package top.jfunc.common.word;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.jfunc.common.datetime.DatetimeUtils;
import top.jfunc.common.excel.ExcelLogs;
import top.jfunc.common.excel.ExcelUtil;
import top.jfunc.common.utils.CharsetUtil;

import java.io.*;
import java.util.List;
import java.util.Map;

public class WordUtil {
    private static final Logger logger = LoggerFactory.getLogger(WordUtil.class);

    private static final String ENCODING = CharsetUtil.UTF_8;
    public static void generateWordFromWordTemplateAndExcelData(String wordTemplateFileName,
                                                                String excelDataFileName,
                                                                File outFile) throws Exception {
    /*String excelDataFileName = "C:\\Users\\Administrator\\Desktop\\数据汇总1.xls";
    String wordTemplateFileName = "C:\\Users\\Administrator\\Desktop\\1.xml";
    String outFileName = "C:\\Users\\Administrator\\Desktop\\yy.doc";*/

        logger.info("wordTemplateFileName:"+wordTemplateFileName);
        logger.info("excelDataFileName:"+excelDataFileName);

        File wordTemplateFile = new File(wordTemplateFileName);
        if(!wordTemplateFile.exists() || !wordTemplateFile.canRead()){
            logger.info("Word模板文件不存在或不可读，请检查");
            return;
        }
        File excelDataFile = new File(excelDataFileName);
        if(!excelDataFile.exists() || !excelDataFile.canRead()){
            logger.info("Excel数据文件不存在或不可读，请检查");
            return;
        }


        //模板的目录位置
        String templateDir = wordTemplateFile.getParent();

        logger.info("templateDir"+templateDir);
        logger.info("即将在"+outFile.getParentFile().getAbsolutePath()+"路径下生成word："+outFile.getName());

        ExcelLogs logs = new ExcelLogs();
        List<Map> mapCollection = (List<Map>) ExcelUtil.importExcel(Map.class, new FileInputStream(excelDataFile), DatetimeUtils.SDF_DATETIME, logs, 0);

        //Configuration 用于读取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding(ENCODING);
        //指定路径的第二种方式，我的路径是F：/test.ftl
        configuration.setDirectoryForTemplateLoading(new File(templateDir));//ftl文件目录
        //以utf-8的编码读取ftl文件
        Template template = configuration.getTemplate(wordTemplateFile.getName(), ENCODING);
        try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), ENCODING), 10240)){
            template.process(mapCollection.get(0), out);
        }
    }
}
